package com.xust.oa.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xust.oa.domain.dto.PageDTO;
import com.xust.oa.domain.entity.Knowledge;
import com.xust.oa.domain.entity.KnowledgeBase;
import com.xust.oa.domain.entity.TermFreq;
import com.xust.oa.service.KnowledgeBaseService;
import com.xust.oa.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author zj
 * @time 2025/3/26 10:16
 */
@RestController
@RequestMapping("/knowledge")
public class KnowledgeController {

    @Autowired
    private KnowledgeBaseService knowledgeBaseService;
    @PostMapping("/getList")
    public Result<List<KnowledgeBase>> getList(@RequestBody PageDTO pageDTO){
        Integer pageNum = pageDTO.getPageNum();
        if (pageNum==null||pageNum<1) pageNum =1;
        Integer pageSize = pageDTO.getPageSize();
        if (pageSize==null||pageSize<1)
            pageSize =10;

        QueryWrapper<KnowledgeBase> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");

        Page<KnowledgeBase> page = new Page<>(pageNum, pageSize);
        return Result.ok(knowledgeBaseService.page(page, queryWrapper).getRecords());
    }

    @GetMapping("/count")
    public Result<Long> getCount(){
        return Result.ok(knowledgeBaseService.count());
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id){
        try {
            knowledgeBaseService.removeById(id);
            return Result.ok("删除成功");
        }catch (Exception e){
            return Result.buildFailure(400,"删除失败");
        }
    }
    @PostMapping("/add")
    public Result add(@RequestBody KnowledgeBase knowledge){
        try {
            knowledge.setId(null);
            if (knowledge.getQuestion()==null||knowledge.getAnswer()==null) throw new RuntimeException("参数错误");
            knowledgeBaseService.save(knowledge);
            return Result.ok("添加成功");
        }catch (Exception e){
            return Result.buildFailure(400,"添加失败");
        }
    }
    @PostMapping("/update")
    public Result update(@RequestBody KnowledgeBase knowledge){
        try {
            if (knowledge==null||knowledge.getId()==null)throw new RuntimeException("id不能为空");
            knowledgeBaseService.updateById(knowledge);
            return Result.ok("修改成功");
        }catch (Exception e){
            return Result.buildFailure(400,"修改失败");
        }
    }
}
